package reviewAlgorithms.ListNode;

public class GetIntersectionNode {
    public static void main(String[] args) {

    }
    public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null ) {
            return null;
        }
        if (headB == null) {
            return null;
        }
        int listCountA = 1;
        int listCountB = 1;
        ListNode res;
        ListNode currentA = headA;
        ListNode currentB = headB;
        while (currentA.next != null){
            listCountA ++;
            currentA = currentA.next;
        }
        while (currentB.next != null){
            listCountB ++;
            currentB = currentB.next;
        }
        if (currentA != currentB){
            return null;
        }else {
            res = getNode(listCountA,listCountB,headA,headB);
        }
        return res;
    }

    private static ListNode getNode(int listCountA, int listCountB, ListNode headA, ListNode headB) {
        if (listCountA < listCountB){
            int temp = listCountA;
            listCountA = listCountB;
            listCountB = temp;
            ListNode nodeTemp = headA;
            headA = headB;
            headB = nodeTemp;
        }
        for (int i = 0; i < listCountA - listCountB; i++) {
            headA = headA.next;
        }
        while (headA != headB){
            headA = headA.next;
            headB = headB.next;
        }
        return headB;
    }
}
